import {
  Controller,
  Get,
  Post,
  UploadedFile,
  UseInterceptors,
  Query,
  BadRequestException,
  Res,
  Body,
  Req,
} from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { FileService } from './file.service';
import { SkipAuth, SkipLogin } from 'src/common/decorator/public.decorator';
import { ConfigService } from '@nestjs/config';
import { Response } from 'express';

@Controller('file')
export class FileController {
  constructor(
    private readonly fileService: FileService,
    private configService: ConfigService,
  ) {}

  /**
   * 上传文件
   * {
   *      fieldname: 'file',
   *      originalname: 'xxxx.png',
   *      encoding: xxx,
   *      mimetype: 'image/png',
   *      buffer: xxx,
   *      size: xxx
   * }
   * @param {*} file
   * @param {*} body
   * @param {*} query
   * @return {*}
   * @memberof FileController
   */
  @SkipLogin()
  @Post('/upload')
  @UseInterceptors(FileInterceptor('file'))
  async upload( @UploadedFile() file: any, @Body() body: any, @Query() query: any ): Promise<any> {
    const maxSize = 1024 * 1024 * 10; // 最大10M
    const allowType = ['png', 'jpeg', 'jpg', 'doc', 'docx', 'ppt'];
    const suffix = (file?.mimetype?.split('/') || []).pop() || '';
    const common = !!(query?.common || body.common || '');

    if (!file) throw new BadRequestException(`未选择文件`);
    if (file.size > maxSize) throw new BadRequestException(`文件最大10M`);
    if (!allowType.includes(suffix))
      throw new BadRequestException(`文件类型错误`);
    if (file.originalname.length > 64)
      throw new BadRequestException(`文件名最多64个字符`);

    const url = await this.fileService.uploadFile(file, common);

    return url;
  }

  // 下载文件
  @SkipLogin()
  @Get('image')
  async getOssFile(@Query() query: any, @Res() res: Response) {
    const { url } = query;
    if (!url) throw new BadRequestException(`无效资源`);
    const fileStream: any = await this.fileService.getFileStream(url);
    res.status(200).send(fileStream || '');
  }

  /**
   * 下载OSS文件，返回下载地址
   *
   * @param {*} req
   * @return {*}
   * @memberof FileController
   */
  @Get('download')
  async downloadFile(@Req() req: any): Promise<any> {
    const { url = '' } = req.query || {};
    const exist = await this.fileService.fileExist(url);
    if (!exist) throw new BadRequestException(`无效请求`);

    return await this.fileService.downloadFile(url);
  }
}
